﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using Medianamik.Core.Logging;
using Telerik.Web.UI;
using Medianamik.UI.Controls;

namespace Medianamik.UI.ConfigManagement
{
    public partial class LogList : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var window = new BaseModalWindow { ID = "purgeLogsWindow" };
            MyWindowManager.Windows.Add(window);
            window.Width = Unit.Pixel(300);
            window.Height = Unit.Pixel(400);
            if (!IsPostBack)
            {
                window.OnClientClose = "modalWindowCallback";
                window.IconUrl = "/Medianamik/images/Icones/Ico_Supprimer.gif";
                window.ReloadOnShow = true;
                window.ShowContentDuringLoad = false;

                var elements = Core.Sugar.Utility.GetEnumElements<LogEntryType>();
                ddlLogType.Items.Add(new ListItem());
                foreach(var element in elements)
                {
                    ddlLogType.Items.Add(new ListItem(Resources("Medianamik_ConfigurationManagement", "LogEntryType_" + element.Value), element.Key.ToString()));
                }
            }
        }
        protected void LogGrid_PageIndexChanged(object sender, GridPageChangedEventArgs e)
        {
            LogGrid.CurrentPageIndex = e.NewPageIndex;
            LogGrid.Rebind();
        }

        protected void LogGrid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            var condition = GetCondition();
            LogGrid.DataSource = LogEntryManager.GetLogEntries(LogGrid.CurrentPageIndex, LogGrid.PageSize, condition);
            LogGrid.VirtualItemCount = LogEntryManager.CountLogEntries(condition);
            LogGrid.AllowCustomPaging = true;
        }

        protected void LogGrid_ItemDataBound(object sender, GridItemEventArgs e)
        {
            var log = (e.Item.DataItem as ILogEntry);
            if (log != null)
            {
                // On détermine si on veut un lien ou un label
                var item = (e.Item as GridDataItem);
                if (item != null)
                {
                    WebControl ctrl;
                    string path = LogEntryManager.GetPathForLog(log);
                    if (!string.IsNullOrEmpty(path))
                    {
                        ctrl = new HyperLink {Text = log.ObjectName, NavigateUrl = path, Target = "_blank"};
                    }
                    else
                    {
                        ctrl = new Label
                                   {
                                       // Cas spécial: le nom d'un log de connexion doit être traduit
                                       Text =
                                           log.Type == LogEntryType.Login
                                               ? Resources("Medianamik_ConfigurationManagement", log.ObjectName)
                                               : log.ObjectName
                                   };
                    }
                    item["ObjectName"].Controls.Add(ctrl);
                }
                var msgLbl = e.Item.FindControl("Message") as Label;
                if (msgLbl != null && !string.IsNullOrEmpty(log.Message))
                {
                    msgLbl.Text = log.Type == LogEntryType.Login 
                                  ? Resources("Medianamik_Global", log.Message) 
                                  : Resources("Medianamik_ConfigurationManagement", "LogMessage_" + log.Message.Replace(' ', '_'));
                }
            }
        }

        protected void RefreshGrid(object sender, EventArgs e)
        {
            LogGrid.Rebind();
        }

        protected void ResetList(object sender, EventArgs e)
        {
            ddlLogType.SelectedIndex = 0;
            datBegins.SelectedDate = null;
            datEnds.SelectedDate = null;
            tbMessage.Text = string.Empty;
            LogGrid.Rebind();
        }

        protected string TranslateType(object type)
        {
            return Resources("Medianamik_ConfigurationManagement", "LogEntryType_" + type);
        }

        protected Dictionary<string, object> GetCondition()
        {
            var expression = new Dictionary<string, object>();
            var dates = new Pair(null, null);
            if (datBegins.SelectedDate.HasValue)
                dates.First = datBegins.SelectedDate;
            if (datEnds.SelectedDate.HasValue)
                dates.Second = datEnds.SelectedDate.Value.AddDays(1).AddSeconds(-1);
            expression.Add("CreatedOn", dates);

            if (tbMessage.Text.Trim().Length > 0)
                expression.Add("Message", tbMessage.Text.Trim());

            if(ddlLogType.SelectedIndex != 0)
            {
                int type;
                if(int.TryParse(ddlLogType.SelectedValue, out type))
                    expression.Add("Type", type);
            }

            if (LogGrid.MasterTableView.SortExpressions.Count > 0)
            {
                GridSortExpression expr = LogGrid.MasterTableView.SortExpressions[0];
                expression.Add("SortCol", expr.FieldName);
                expression.Add("SortOrd", expr.SortOrder == GridSortOrder.Ascending ? "ASC" : "DESC");
            }
            return expression;
        }
    }
}
